﻿using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows;
using System.Collections;
using DBCTools.Tools;
using System;

namespace dbcTools.Tools
{
	public class dbcReader :  dbcStruct
	{
		public dbcReader(string file)
		{
			hasPrimarykey = true;
			if (!File.Exists(file))
				throw new Exception(file + "文件不存在.");

			StreamReader sr = new StreamReader(file);
			BinaryReader br = new BinaryReader(sr.BaseStream);

			if (1128416343 != br.ReadUInt32())
			{
				MessageBox.Show("文件[" + file + "]不是标准的dbc文件!");
				return;
			}
			dbcStore1 = new Dictionary<uint, byte[]>();
			RowCount = br.ReadUInt32();
			ColumnCount = br.ReadUInt32();
			RowSize = br.ReadUInt32();
			StringBlockSize = br.ReadUInt32();

			for (uint i = 0; i < RowCount; i++)
			{
				byte[] rowData = br.ReadBytes((int)RowSize);

				MemoryStream ms = new MemoryStream(rowData);
				
				uint entry = (uint)ms.ReadByte();
				if (hasPrimarykey && !dbcStore1.ContainsKey(entry))
					dbcStore1.Add(entry, rowData);
				else if (!hasPrimarykey)
					dbcStort2.Add(i, rowData);
				else if(hasPrimarykey && dbcStore1.ContainsKey(entry))
				{
					dbcStort2 = new Dictionary<uint, byte[]>();
					uint zz = 0;
					foreach (var z in dbcStore1)
					{
						dbcStort2.Add(zz++,z.Value);
					}
					dbcStort2.Add(i, rowData);
					dbcStore1 = null;
					hasPrimarykey = false;
				}
			}
			StringBlock = br.ReadBytes((int)StringBlockSize);

			br.Close();
		}
	}
}
